package com.uroad.jilinpda.common;

import android.app.Activity;
import android.app.Application;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.multidex.MultiDex;
import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;
import com.genvict.handset.GvHandsetInterface;
import com.uroad.jilinpda.R;
import com.uroad.jilinpda.http.OkHttpNetWork;
import com.uroad.jilinpda.http.OkHttpNetWorkCallBack;
import com.uroad.jilinpda.modle.UserMDL;
import com.uroad.jilinpda.util.AppUtils;
import com.uroad.jilinpda.util.GvApiResult;
import com.uroad.jilinpda.util.ImeiUtil;
import com.uroad.jilinpda.util.NetWorkUtil;
import com.uroad.jilinpda.util.SPUtils;
import com.uroad.jilinpda.util.SdkHelper;
import com.uroad.jilinpda.webservice.ActivateWS;
import com.uroad.jilinpda.webservice.BaseWS;
import com.uroad.lib.data.Constant;
import com.uroad.lib.json.FastJsonUtils;
import com.uroad.lib.util.log.LogUtil;
import com.uroad.lib.widget.dialog.DialogHelper;

import java.util.HashMap;

import static com.uroad.jilinpda.webservice.BaseWS.getNewUrl;


/**
 * @创建者 wlw
 * @创建时间 2018/11/16 17:13
 * @描述
 */
public class CurrApplication extends Application {
    public static final String DEV_MODEL_M700 = "M700";
    public static final String DEV_MODEL_P700 = "JDN-AL00";

    public static String STATION_LANE = "01";

    private static CurrApplication instance = null;

    /*public static UserMDL      user   = null;
    public static LoginMDL worker   = null;
    public static GetNetPoiMDL netpoi = null;*/

//    private GvHandsetInterface handsetSDK;
    /*private SdkHelper sdkHelper;

    public DaoUtils daoUtils;
    public static ImageLoaderHelperNew mLoader;*/

    /**
     * 保存前三次交易车牌号 防止重复交易
     */
    public static String licensePlates = "";

    /**
     * 未上传出口6637消息数量
     */
    public static int expassnum = 0;

    // 手机imei
    public String deviceuuid;
    // 手机操作系统版本
    public String deviceversion;
    // 手机机型
    public String devicemodel;
    public String deviceName;
    // 应用程序名
    private String appname;
    // 应用版本号
    public String appversion;
    // 登录用户信息
    public static UserMDL userLoginer;
    public static UserMDL user = null;
    boolean isRunInBackground = true;
    private int appCount;
    private SdkHelper sdkHelper;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        initIsDebug();
        autoInitSDK();
        initBaseUrl();
        getDeviceInfo();
        initBackgroundCallBack();
    }

    /**
     * 异常收集
     */
    private void initCashHandler() {
//        CrashHandler.getInstance().init(this);
    }

    /**
     * 是否debug判断
     */
    private void initIsDebug() {
        AppUtils.syncIsDebug(this);
    }

    private void initSQL() {
//        daoUtils = new DaoUtils(this);
    }

    public static int getExpassnum() {
        return expassnum;
    }

    public static void setExpassnum(int expassnum) {
        CurrApplication.expassnum = expassnum;
    }

    public static CurrApplication getInstance() {
        return instance;
    }


   private void initBaseUrl() {
        Constant.BASE_URL = BaseWS.new_url;
        Constant.BASE_URL_4G = BaseWS.new_url_4g;
        /*String curNet = NetWorkUtil.getCurrNetWork(this);
        Constant.NET = curNet;
        boolean ischeckNetwork = (boolean) SPUtils.get(this, GlobalData.sp_auto_check_network, true);
        GlobalData.isCheckNetwork = ischeckNetwork;
        if (ischeckNetwork) {//自动检测网络
            if ("4G".equalsIgnoreCase(curNet)) {
                NetWorkUtil.checkNetwork(this);
            } else {
                Constant.NET = "WIFI";
            }
        }else{
            Constant.NET = (String) SPUtils.get(this, GlobalData.sp_set_network, "WIFI");
        }*/
       Constant.NET = (String) SPUtils.get(this, GlobalData.sp_set_network, "WIFI");
    }



    public void getDeviceInfo() {
        try {
            deviceuuid = ImeiUtil.getMyImei(this);//六合一信息
            SPUtils.put(this, GlobalData.sp_deviceuuid, deviceuuid);
            deviceversion = Build.VERSION.RELEASE;//安卓版本
            devicemodel = Build.MODEL;//手机型号
            BluetoothAdapter myDevice = BluetoothAdapter.getDefaultAdapter();
            if (myDevice != null) {
                deviceName = myDevice.getName();
            }else{
                deviceName = devicemodel;
            }
            appname = getResources().getString(R.string.app_name); //app名称

            PackageManager manager = getPackageManager();
            PackageInfo info = manager.getPackageInfo(getPackageName(), 0);
            appversion = info.versionName; //app版本
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getDeviceuuid() {
        return deviceuuid == null ? "" : deviceuuid;
    }

    public void setDeviceuuid(String deviceuuid) {
        this.deviceuuid = deviceuuid;
    }

    public void setUserLoginer(UserMDL userLoginer) {
        this.userLoginer = userLoginer;
    }

    private void initBackgroundCallBack() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            }

            @Override
            public void onActivityStarted(Activity activity) {
                appCount++;
                if (isRunInBackground) {
                    //应用从后台回到前台 需要做的操作
                    back2App(activity);
                }
            }

            @Override
            public void onActivityResumed(Activity activity) {
            }

            @Override
            public void onActivityPaused(Activity activity) {
            }

            @Override
            public void onActivityStopped(Activity activity) {
                appCount--;
                if (appCount == 0) {
                    //应用进入后台 需要做的操作
                    leaveApp(activity);
                }
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
            }
        });
    }

    private void back2App(Activity activity) {
        online();
    }

    public void online() {
        if (TextUtils.isEmpty(deviceuuid)) {
            getDeviceInfo();
        }
        isRunInBackground = false;
        doRequest(ActivateWS.online, ActivateWS.onlineParams(deviceversion, devicemodel,
                appversion, deviceuuid, deviceName), ActivateWS.online);
    }

    private void leaveApp(Activity activity) {
        isRunInBackground = true;
        if (TextUtils.isEmpty(deviceuuid)) {
            getDeviceInfo();
        }
        doRequest(ActivateWS.offline, ActivateWS.offlineParams(deviceuuid), ActivateWS.offline);
    }

    public void doRequest(final String methodUrl, HashMap params,
                          final String type){
        OkHttpNetWork netWork = new OkHttpNetWork(this);
        netWork.doAllUrlRequest(getNewUrl(methodUrl), params, methodUrl, new OkHttpNetWorkCallBack() {
            @Override
            public void OnHttpNetWork(String type) {
                CurrApplication.this.OnHttpNetWork(type);
            }

            @Override
            public void OnHttpFailure(String type, String msg) {
                CurrApplication.this.OnHttpFailure(type);
            }

            @Override
            public void OnHttpTaskComplete(String result, String type) {
                CurrApplication.this.OnHttpTaskComplete(result,type);
            }
        });
    }

    private void OnHttpTaskComplete(String result, String type) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (FastJsonUtils.GetJsonStatu1(jsonObject)) {
                if (ActivateWS.online.equals(type)) {
                    LogUtil.i("CurrApplication","=====device online success=====");
                    String data = FastJsonUtils.getData(jsonObject);
                    if (!TextUtils.isEmpty(data)) {
                        UserMDL user = FastJsonUtils.parseObjectJSON(data, UserMDL.class);
                        this.user = user;
                        if (user != null) {
                            SPUtils.put(this, GlobalData.sp_ticketid, user.getTicketid());
                            SPUtils.put(this, GlobalData.sp_useruuid, user.getUseruuid());
                            SPUtils.put(this, GlobalData.sp_phone, user.getPhone());
                            SPUtils.put(this, GlobalData.sp_username, user.getUsername());
                            SPUtils.put(this, GlobalData.sp_icon, user.getIcon());
                            SPUtils.put(this, GlobalData.sp_recocode, user.getRecocode());
                            SPUtils.put(this, GlobalData.sp_usertype, user.getUsertype());
                            SPUtils.put(this, GlobalData.sp_number, user.getNumber());
                        } else {
                            clearUser();
                        }
                    } else {
                        //未登录
                        clearUser();
                    }
                } else if (ActivateWS.offline.equals(type)) {
                    LogUtil.i("CurrApplication","=====device offline success=====");
                }
            } else {
                DialogHelper.showShortTost(this, FastJsonUtils.GetErrorString(jsonObject, "msg"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void clearUser() {
        this.user = null;
        SPUtils.remove(this, GlobalData.sp_ticketid);
        SPUtils.remove(this, GlobalData.sp_useruuid);
        SPUtils.remove(this, GlobalData.sp_phone);
        SPUtils.remove(this, GlobalData.sp_username);
        SPUtils.remove(this, GlobalData.sp_icon);
        SPUtils.remove(this, GlobalData.sp_recocode);
    }

    private void OnHttpNetWork(String type) {
        LogUtil.i("CurrApplication","=====no intent=====" + type);
    }

    private void OnHttpFailure(String type) {
        LogUtil.i("CurrApplication","=====on http fail=====" + type);
    }


    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }


    /**
     * 自动根据系统信息的设备类型进行sdk的初始化
     */
    private void autoInitSDK() {
        sdkHelper = SdkHelper.getInstance(this);
//        String devModel = Build.MODEL;
//        System.out.println("Device Model: " + devModel);
//        if (devModel.equals(DEV_MODEL_P700)) {
//            handsetSDK = new ObuInterface(this, SdkConstant.HANDSET_TYPE_P700);
//        } else {
//            handsetSDK = new ObuInterface(this, SdkConstant.HANDSET_TYPE_M700);
//        }
    }
    /**
     * 打开天线设备
     * @return GvApiResult 0成功，非0失败
     */
    public int openDsrc() {
        GvApiResult result = sdkHelper.openDsrc();
        if (result == GvApiResult.SUCCESS) {
            return 0;
        } else {
            return result.getCode();
        }
    }

    /**
     * 关闭天线设备
     * @return GvApiResult 0成功，非0失败
     */
    public int closeDsrc() {
        if (sdkHelper != null) {
            GvApiResult result = sdkHelper.closeDsrc();
            if (result == GvApiResult.SUCCESS) {
                return 0;
            } else {
                return result.getCode();
            }
        } else {
            return -1;
        }
    }

    /**
     * 获取手持机SDK实例
     * @return GvHandsetInterface对象实例
     */
    public GvHandsetInterface getHandsetSDK() {
//        Log.i("","getHandsetSDK");
        return sdkHelper.getSdk();
//        return handsetSDK;
    }
}
